<?php
declare (strict_types = 1);

namespace app\user\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class UserAddress extends Model
{
    public $page = '';//分页数据
    public $count = '';//数据总数
    public $error = '';//报错


    /*
     * 获取收货地址
     */
    public function myAddrList($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            $where = ['a.uid'=>$id,'a.is_delete'=>0];
            if(!empty($data['id'])) $where['a.id']=$data['id'];
            $field = 'a.id,a.address,a.tel,a.name,a.is_default,a.add_time,d.name as province,ad.name as city,ds.name as area';
            $res = $this->alias('a')->join('district d','d.id=a.province','left')->join('district ad','ad.id=a.city','left')
                ->join('district ds','ds.id=a.area','left')->field($field)->where($where)
                ->order('a.is_default desc,a.add_time desc')->select();
            return $res;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 添加收获地址
     */
    public function addAddress($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            if(empty($data['id'])){
                if(empty($data['tel'])) exception('请填写手机号!');
                if(!preg_match("/^1[3456789]\d{9}$/", $data['tel'])) exception('请填写正确的手机号');
                if(empty($data['name'])) exception('请填写用户名!');
                if(empty($data['province'])||empty($data['province_sn'])) exception('请选择省!');
                if(empty($data['city'])||empty($data['city_sn'])) exception('请选择市!');
                if(empty($data['area'])||empty($data['area_sn'])) exception('请选择区!');
                if(empty($data['address'])) exception('请填写详细地址!');
                if(!isset($data['is_default'])){
                    $count = $this->where(['uid'=>$id,'is_delete'=>0])->count();
                    if($count > 0) $data['is_default'] = 0;
                    else $data['is_default'] = 1;
                }else{
                    if(!empty($data['is_default'])&&$data['is_default']==1) $is_default = $this->where(['uid'=>$id,'is_default'=>1,'is_delete'=>0])->update(['is_default'=>0]);#将其他记录取消默认
                }
                #判断地区表，不存在则更新地区表记录
                $this->addDistrict($data);
                #添加用户提交收货地址
                $this->insert([
                    'uid'=>$id,
                    'tel'=>$data['tel'],
                    'name'=>$data['name'],
                    'province'=>$data['province_sn'],
                    'city'=>$data['city_sn'],
                    'area'=>$data['area_sn'],
                    'address'=>$data['address'],
                    'is_default'=>$data['is_default'],
                    'add_time'=>time(),
                ]);
            }else{
                $info = $this->where(['id'=>$data['id'],'uid'=>$id,'is_delete'=>0])->find();
                if(empty($info)) exception('找不到这条地址记录!');
                if(!empty($data['tel'])&&!preg_match("/^1[3456789]\d{9}$/", $data['tel'])) exception('请填写正确的手机号');
                if(!empty($data['province_sn'])&&!empty($data['city_sn'])&&!empty($data['area_sn']))
                    $this->addDistrict($data);#判断地区表，不存在则更新地区表记录
                if(isset($data['is_default'])&&$data['is_default'] == 1){
                    $is_default = $this->where(['uid'=>$id,'is_default'=>1,'is_delete'=>0])->update(['is_default'=>0]);#将其他记录取消默认
                }
                #编辑用户提交收货地址
                $this->where(['id'=>$info['id']])->update([
                    'tel' => empty($data['tel']) ? $info['tel'] : $data['tel'],
                    'name' => empty($data['name']) ? $info['name'] : $data['name'],
                    'province' => empty($data['province_sn']) ? $info['province'] : $data['province_sn'],
                    'city' => empty($data['city_sn']) ? $info['city'] : $data['city_sn'],
                    'area' => empty($data['area_sn']) ? $info['area'] : $data['area_sn'],
                    'is_default'=>empty($data['is_default']) ? $info['is_default'] : $data['is_default'],
                    'address' => empty($data['address']) ? $info['address'] : $data['address'],
                ]);
            }
            return true;
        }catch (\Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 删除收获地址
     */
    public function delAddress($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            if(empty($data['id'])) exception('请选择要删除的收货地址!');
            $info = $this->where(['id'=>$data['id'],'uid'=>$id])->find();
            if(!empty($info)){
                if($info['is_default'] == 1){ #如果删除的是默认地址，则修改最新添加的一条地址为默认
                    $default = $this->where(['uid'=>$id,'is_delete'=>0])->whereNotIn('id',[$info['id']])->order('add_time')->find();
                    if(!empty($default)) $this->where(['id'=>$default['id']])->update(['is_default'=>1]);
                }
                $this->where(['id'=>$info['id']])->update(['is_delete'=>1]);
                return true;
            }else exception('删除失败!');
            return false;
        }catch (\Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }

    /*
     * 更新地区表
     */
    public function addDistrict($data)
    {
        $model = new District();
        $district = $model->whereIn('id',[$data['province_sn'],$data['city_sn'],$data['area_sn']])->select();
        if(!empty($district) && count($district) < 3){
            #如果地区表不全，则补录数据
            $addr = [];
            $dis = ['province'=>$data['province_sn'],'city'=>$data['city_sn'],'area'=>$data['area_sn']];
            foreach($district as $v){
                if($v['id'] == $data['province_sn']) $addr['province'] = $v['id'];
                if($v['id'] == $data['city_sn']) $addr['city'] = $v['id'];
                if($v['id'] == $data['area_sn']) $addr['area'] = $v['id'];
            }
            $diff = array_diff($dis,$addr);
            #取差值遍历插入数据库
            if($diff){
                foreach($diff as $key=>$val){
                    if($key == 'province')
                        $model->insert(['id'=>$val,'pid'=>0,'name'=>$data[$key],'level'=>1]);
                    if($key == 'city')
                        $model->insert(['id'=>$val,'pid'=>$data['province_sn'],'name'=>$data[$key],'level'=>2]);
                    if($key == 'area')
                        $model->insert(['id'=>$val,'pid'=>$data['city_sn'],'name'=>$data[$key],'level'=>3]);
                }
            }
        }
    }

}
